<!--
 * @Descripttion:
 * @version:
 * @Date: 2021-04-20 11:06:21
 * @LastEditors: huzhushan@126.com
 * @LastEditTime: 2022-09-27 18:24:27
 * @Author: huzhushan@126.com
 * @HomePage: https://huzhushan.gitee.io/vue3-element-admin
 * @Github: https://github.com/huzhushan/vue3-element-admin
 * @Donate: https://huzhushan.gitee.io/vue3-element-admin/donate/
-->
<template>
  <div class="login">
    <el-form
      class="form"
      :model="user"
      ref="UserForm"
      :rules="userRules"
      v-show="pass === true"
    >
      <el-form-item prop="realName">
        <el-input
          class="text"
          v-model="user.realName"
          prefix-icon="UserFilled"
          clearable
          placeholder="真实姓名"
        />
      </el-form-item>
      <el-form-item prop="iden">
        <el-input
          class="text"
          v-model="user.iden"
          prefix-icon="EditPen"
          clearable
          placeholder="身份证号"
        />
      </el-form-item>
      <el-form-item prop="mobile">
        <el-input
          class="text"
          v-model="user.mobile"
          prefix-icon="Phone"
          clearable
          placeholder="手机号"
        />
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          class="text"
          v-model="user.password"
          prefix-icon="Lock"
          show-password
          clearable
          placeholder="输入密码"
        />
      </el-form-item>
      <el-form-item prop="password2">
        <el-input
          class="text"
          v-model="user.password2"
          prefix-icon="Lock"
          show-password
          clearable
          @blur="selectPassword"
          placeholder="确人密码"
        />
      </el-form-item>
      <el-form-item>
        <el-input
          class="text"
          v-model="user.chk"
          clearable
          placeholder="验证码"
          input-style="width: 300px"
        />
        <el-button
          type="text"
          style="margin-left: 60px;height: 45px"
          @click="getChk"
          :disabled="disabled"
        >
          {{ btntxt }}
        </el-button>
      </el-form-item>
      <el-form-item>
        <el-button
          :loading="loading"
          type="primary"
          class="btn"
          size="large"
          @click="updatePassword"
        >
          确定
        </el-button>
      </el-form-item>
    </el-form>

    <!--手机号验证-->
    <el-form
      class="form"
      :model="phone"
      ref="phoneForm"
      :rules="rules"
      v-show="look === true"
    >
      <el-form-item prop="mobile">
        <el-input
          class="text"
          v-model="phone.mobile"
          prefix-icon="phone"
          clearable
          placeholder="手机号"
        />
      </el-form-item>
      <el-form-item>
        <el-input
          class="text"
          v-model="phone.chk"
          prefix-icon="password"
          clearable
          placeholder="验证码"
          input-style="width: 300px"
        />
        <el-button
          type="text"
          style="margin-left: 60px;height: 45px"
          @click="getChk"
          :disabled="disabled"
        >
          {{ btntxt }}
        </el-button>
      </el-form-item>
      <el-form-item>
        <el-button
          :loading="loading"
          type="primary"
          class="btn"
          size="large"
          @click="phoneLogin"
        >
          {{ btnText }}
        </el-button>
        <el-button type="text" @click="topassword">
          点击此处进行密码登录
        </el-button>
      </el-form-item>
    </el-form>

    <!--手机号密码-->
    <el-form
      class="form"
      :model="model"
      :rules="rules"
      ref="loginForm"
      v-show="login === true"
    >
      <el-form-item prop="mobile">
        <el-input
          class="text"
          v-model="model.mobile"
          prefix-icon="phone"
          clearable
          placeholder="手机号"
        />
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          class="text"
          v-model="model.password"
          prefix-icon="Lock"
          show-password
          clearable
          placeholder="密码"
        />
      </el-form-item>

      <el-form-item prop="captcha">
        <div class="captcha">
          <el-input
            class="text"
            v-model="model.captcha"
            prefix-icon="Picture"
            placeholder="请输入验证码"
          ></el-input>
          <img :src="captchaSrc" @click="refreshCaptcha" />
        </div>
      </el-form-item>
      <el-form-item>
        <el-button
          :loading="loading"
          type="primary"
          class="btn"
          size="large"
          @click="submit"
        >
          {{ btnText }}
        </el-button>
        <el-button type="text" @click="toMobile">
          点击此处进行短信验证码登录
        </el-button>
        <el-button
          type="text"
          @click="getpassword"
          style="padding-left: 190px;"
        >
          忘记密码
        </el-button>
      </el-form-item>
    </el-form>
  </div>
  <div class="change-lang">
    <change-lang />
  </div>
</template>

<script>
import {
  defineComponent,
  getCurrentInstance,
  reactive,
  toRefs,
  ref,
  computed,
  watch,
  onMounted,
} from 'vue'
import { GetValidateCode, Login, phone, send, updatePass } from '@/api/login'
import { useRouter, useRoute } from 'vue-router'
import ChangeLang from '@/layout/components/Topbar/ChangeLang.vue'
import useLang from '@/i18n/useLang'
import { useApp } from '@/pinia/modules/app'
import { ElMessage } from 'element-plus'

export default defineComponent({
  components: { ChangeLang },
  name: 'login',
  setup() {
    const { proxy: ctx } = getCurrentInstance() // 可以把ctx当成vue2中的this
    const router = useRouter()
    const route = useRoute()
    const { lang } = useLang()

    watch(lang, () => {
      state.rules = getRules()
    })

    watch(lang, () => {
      state.userRules = getUserRules()
    })

    const getUserRules = () => ({
      iden: [
        {
          required: true,
          message: '请输入身份证号',
          trigger: 'blur',
        },
        {
          pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
          message: '请输入正确的身份证号',
          trigger: 'blur',
        },
      ],
      mobile: [
        {
          required: true,
          message: '请输入手机号',
          trigger: 'blur',
        },

        {
          pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
          message: '请输入正确的手机号码',
          trigger: 'blur',
        },
      ],
      password: [
        {
          required: true,
          message: ctx.$t('login.rules-password'),
          trigger: 'blur',
        },
        {
          pattern: /(?!^(\d+|[a-zA-Z]+|[~!@#$%^&*?]+)$)^[\w~!@#$%^&*?]{7,20}$/,
          message: '密码8-16位，需字母+数字+字符至少两种',
          trigger: 'blur',
        },
      ],
    })
    const getRules = () => ({
      //手机号正则
      mobile: [
        {
          required: true,
          message: '请输入手机号',
          trigger: 'blur',
        },

        {
          pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
          message: '请输入正确的手机号码',
          trigger: 'blur',
        },
      ],
      password: [
        {
          required: true,
          message: ctx.$t('login.rules-password'),
          trigger: 'blur',
        },
        {
          min: 6,
          max: 12,
          message: ctx.$t('login.rules-regpassword'),
          trigger: 'blur',
        },
      ],
    })
    // onMounted钩子函数
    onMounted(() => {
      state.refreshCaptcha()
    })
    const state = reactive({
      model: {
        mobile: '',
        password: '',
        captcha: '', // 用户输入的验证码
        codeKey: '', // 后端返回的验证码key
      },
      phone: {
        mobile: '',
        chk: '',
      },
      user: {
        mobile: '',
      },
      btntxt: '获取验证码',
      pass: false,
      login: true,
      disabled: false,
      time: 60,
      look: false,
      rules: getRules(),
      userRules: getUserRules(),
      loading: false,
      captchaSrc: '',

      updatePassword: async () => {
        const { data, code, message } = await updatePass(state.user)
        if (code !== 200) {
          alert(message)
        } else if (code === 200) {
          alert('修改成功')
          location.reload()
        }
      },
      //判断两次密码是否一样
      selectPassword: () => {
        if (state.user.password != state.user.password2) {
          alert('两次密码输入不一样')
        }
      },
      //手机号验证码登录
      toMobile: () => {
        state.look = true
        state.login = false
      },
      //手机号密码登录页面
      topassword: () => {
        state.login = true
        state.look = false
      },
      getpassword: () => {
        state.pass = true
        state.look = false
        state.login = false
      },
      //获取短信验证码
      getChk: () => {
        // if(state.phone.mobile.length===0 || state.user.mobile.length===0){
        //   alert("还未添手机号")
        // }
        state.time = 59
        state.disabled = true
        state.timer()
        if (state.phone.mobile.length !== 0) {
          send(state.phone.mobile)
        } else if (state.user.mobile.length !== 0) {
          send(state.user.mobile)
        }
      },
      timer: function() {
        if (state.time > 0) {
          state.time = state.time - 1
          //           console.log(state.time);
          state.btntxt = state.time + 's后重新获取'
          setTimeout(state.timer, 1000)
        } else {
          state.time = 0
          state.btntxt = '获取验证码'
          state.disabled = false
        }
      },

      refreshCaptcha: async () => {
        const { data } = await GetValidateCode()
        //响应验证码ikey  保存到redis中的key
        state.model.codeKey = data.codeKey
        //图片验证码
        state.captchaSrc = data.codeValue
      },
      btnText: computed(() =>
        state.loading ? ctx.$t('login.logining') : ctx.$t('login.login')
      ),
      loginForm: ref(null),
      submit: () => {
        if (state.loading) {
          return
        }
        state.loginForm.validate(async valid => {
          if (valid) {
            // state.loading = true
            const { code, data, message } = await Login(state.model)
            if (+code === 200) {
              ctx.$message.success({
                message: ctx.$t('login.loginsuccess'),
                duration: 1000,
              })
              if (+code !== 200) {
                ctx.$message.error('s')
              }

              const targetPath = decodeURIComponent(route.query.redirect)
              if (targetPath.startsWith('http')) {
                // 如果是一个url地址
                window.location.href = targetPath
              } else if (targetPath.startsWith('/')) {
                // 如果是内部路由地址
                router.push(targetPath)
              } else {
                router.push('/')
              }
              useApp().initToken(data)
            } else {
              ctx.$message.error(message)
            }
            state.loading = false
          }
        })
      },

      phoneForm: ref(null),
      phoneLogin: () => {
        if (state.loading) {
          return
        }
        state.phoneForm.validate(async valid => {
          if (valid) {
            // state.loading = true
            const { code, data, message } = await phone(state.phone)
            if (+code === 200) {
              ctx.$message.success({
                message: ctx.$t('login.loginsuccess'),
                duration: 1000,
              })
              if (+code !== 200) {
                ctx.$message.error('s')
              }

              const targetPath = decodeURIComponent(route.query.redirect)
              if (targetPath.startsWith('http')) {
                // 如果是一个url地址
                window.location.href = targetPath
              } else if (targetPath.startsWith('/')) {
                // 如果是内部路由地址
                router.push(targetPath)
              } else {
                router.push('/')
              }
              useApp().initToken(data)
            } else {
              ctx.$message.error(message)
            }
            state.loading = false
          }
        })
      },
    })

    return {
      ...toRefs(state),
    }
  },
})
</script>

<style lang="scss" scoped>
.login {
  transition: transform 1s;
  transform: scale(1);
  width: 100%;
  height: 100%;
  overflow: hidden;
  //background: #2d3a4b;
  background-image: url('../../assets/beijing.png');
  background-size: cover;
  .form {
    width: 520px;
    max-width: 100%;
    padding: 0 24px;
    box-sizing: border-box;
    margin: 300px auto 0;
    margin-left: 1100px;
    :deep {
      .el-input__wrapper {
        box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.1) inset;
        background: rgba(0, 0, 0, 0.1);
      }
      .el-input-group--append > .el-input__wrapper {
        border-top-right-radius: 0;
        border-bottom-right-radius: 0;
      }
      .el-input-group--prepend > .el-input__wrapper {
        border-top-left-radius: 0;
        border-bottom-left-radius: 0;
      }
    }
    .title {
      color: #fff;
      text-align: center;
      font-size: 24px;
      margin: 0 0 24px;
    }
    .text {
      font-size: 16px;
      :deep(.el-input__inner) {
        color: #fff;
        height: 48px;
        line-height: 48px;
        &::placeholder {
          color: rgba(255, 255, 255, 0.2);
        }
      }
    }
    .btn {
      width: 100%;
    }
  }
}

.captcha {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
}

.captcha img {
  cursor: pointer;
  margin-left: 20px;
}

.change-lang {
  position: fixed;
  right: 20px;
  top: 20px;
  :deep {
    .change-lang {
      height: 24px;
      &:hover {
        background: none;
      }
      .icon {
        color: #fff;
      }
    }
  }
}
</style>
